package com.hyh.baowenlioaworking.exception;


import com.hyh.baowenlioaworking.commom.Constants;
import com.hyh.baowenlioaworking.commom.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @BelongsPackage: com.hyh.baowenlioaworking.exception
 * @ClassName GlobalExceptionHandler
 * @Author: hyhWTX
 * @CreateTime: 2023-07-21  16:26
 * @Description: TODO (一句话描述以下该类的功能)
 * @Version: 1.0
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExceptionHandler {
    /**
     * @ExceptionHandler相当于controller的@RequestMapping
     * 如果抛出的是ServiceException，则调用该方法
     * @param se 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public R handle(ServiceException se) {
        return R.error(se.getCode(),se.getMessage());
    }
    /**
     * 进行异常处理方法
     * @param ex 异常对象，后面Get信息要用
     * @return 返回Result对象，既然都抓异常了，肯定就要Result.error("失败信息")
     * @ExceptionHandler({异常类型.class,异常类型.class})
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error(ex.getMessage());
        //判断出来的异常信息
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] filelds = ex.getMessage().split(" ");
            /**
             * * splitErrorMessage数组内存的信息
             * Duplicate entry '新增的账号' for key 'idx_username'
             * 下标位2是新增账号，下标位5是关联的字段名
             */
            String message = "这个账号重复了" + filelds[2];
            return R.error(Constants.CODE_500, message);
        }
        return R.error(Constants.CODE_600, "未知错误！");
    }
    /**
     * 在全局异常处理器上添加自定义的异常
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomerException.class)
    public R<String> exceptionHandler(CustomerException ex) {
        log.error(ex.getMessage());

        return R.error(Constants.CODE_200,ex.getMessage());

    }

    }

